package com.itheima.admin.contorller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.admin.config.AliyunConfig;
import com.itheima.common.result.JsonResult;
import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @author : sky
 * @date : 2023/3/3 19:50
 * @modyified By :
 */
@RestController
@RequestMapping("common")
@Log4j2
@Api(tags = "图片上传")
public class CommonController {
    @Autowired
    private AliyunConfig aliyunConfig;
       public JsonResult uploadPics(@RequestBody MultipartFile file){
        //获取文件名
           String filename = file.getOriginalFilename();
           //创建ossclient实例
           OSS ossClient = new OSSClientBuilder().
                   build(aliyunConfig.getEndpoint(),
                           aliyunConfig.getAccessKeyId(),
                          aliyunConfig.getAccessKeySecret());
           //上传文件
           try {
               ossClient.putObject(aliyunConfig.getBucketName(),
                       filename,
                       new ByteArrayInputStream(file.getBytes()));
           } catch (IOException e) {
              log.error("上传文件错误！");
           } finally {
           //上传完成，关闭服务器
               if (ossClient !=null){
                   ossClient.shutdown();
               }
           }
           //返回结果
           return JsonResult.success(aliyunConfig.getUrlPrefix()+"/"+filename);
    }
}

